import { breadFirstTree } from '@/utils/util'
const storeQueryPages = []

// 前端路由表
export const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: () => import('@/layouts/BasicLayout'),
  BlankLayout: () => import('@/layouts/BlankLayout'),
  RouteView: () => import('@/layouts/RouteView'),
  PageView: () => import('@/layouts/PageView'),
  DashboardLayout: () => import('@/layouts/DashboardLayout'),
  Welcome: () => import('@/views/Welcome'),
  Dashboard: () => import('@/views/dashboard/Index'),
  404: () => import('@/views/exception/404'),

  // 认证中心
  MenuConfig: () => import('@/views/authenticationCenter/MenuConfig'),
  RoleConfig: () => import('@/views/authenticationCenter/RoleConfig'),
  RoleForm: () => import('@/views/authenticationCenter/RoleForm'),
  UserGroup: () => import('@/views/authenticationCenter/userGroup'),
  AuthenticationConfig: () => import('@/views/authenticationCenter/authenticationConfig/Index'),
  LoginConfig: () => import('@/views/authenticationCenter/authenticationConfig/LoginConfig'),
  SecurityConfiguration: () => import('@/views/authenticationCenter/authenticationConfig/SecurityConfiguration'),
  // 人员
  StructureUserInfo: () => import('@/views/authenticationCenter/structure/UserInfo'),
  StructureUser: () => import('@/views/authenticationCenter/structure/User'),
  StructureList: () => import('@/views/authenticationCenter/structure/List'),

  // 平台管理
  Company: () => import('@/views/platformManagement/company/Index'),
  CompanyBaseInfo: () => import('@/views/platformManagement/company/BaseSetting'),
  CompanySettings: () => import('@/views/platformManagement/company/msgSetting/index'),
  CompanyMailConfig: () => import('@/views/platformManagement/company/msgSetting/MailConfig'),
  CompanySysInfo: () => import('@/views/platformManagement/company/msgSetting/SysInfo'),
  CompanyWxConfig: () => import('@/views/platformManagement/company/msgSetting/CompanyWxConfig'),

  ApplicationsList: () => import('@/views/platformManagement/application/List'),
  ApplicationsInfo: () => import('@/views/platformManagement/application/Item'),
  ApplicationBaseDataConfig: () => import('@/views/platformManagement/application/BaseDataConfig'),
  ApplicationMessageConfig: () => import('@/views/platformManagement/application/messageConfig'),
  ApplicationSysInfo: () => import('@/views/platformManagement/application/messageConfig/SysInfo'),
  ApplicationCompanyWxConfig: () => import('@/views/platformManagement/application/messageConfig/CompanyWxConfig'),
  ApplicationMailConfig: () => import('@/views/platformManagement/application/messageConfig/MailConfig'),

  Account: () => import('@/views/platformManagement/account/Index'),
  AccountBaseInfo: () => import('@/views/platformManagement/account/BaseInfo'),
  AccountSecurity: () => import('@/views/platformManagement/account/Security'),
  AccountShiftConfig: () => import('@/views/platformManagement/account/ShiftConfig'),

  SysOperationLog: () => import('@/views/platformManagement/log/SysOperationLog'),
  LoginLog: () => import('@/views/platformManagement/log/LoginLog'),


  // 技术库
  UdaDatasheet: () => import('@/views/technology/Uda/Datasheet'),
  UdaSetExtension: () => import('@/views/technology/Uda/SetExtension'),
  SerialNumberManage: () => import('@/views/technology/serial/SerialNumberManage'),
  DictSetting: () => import('@/views/technology/dict/DictSetting'),

  // 消息中心
  Message: () => import('@/views/messageCenter/message'),
  Notice: () => import('@/views/messageCenter/notice'),
  MessageTemplate: () => import('@/views/messageCenter/template'),
  MessageTemplateDetail: () => import('@/views/messageCenter/template/Detail'),
  Escalate: () => import('@/views/messageCenter/escalate'),
  EscalateDetail: () => import('@/views/messageCenter/escalate/Detail'),

  // 打印服务
  PrintHistory: () => import('@/views/printService/PrintHistory'),
  Printer: () => import('@/views/printService/Printer'),
  PrintTemplate: () => import('@/views/printService/PrintTemplate'),

  // edge管理
  EdgeConfig: () => import('@/views/edgeManagement/EdgeConfig'),
  EdgeList: () => import('@/views/edgeManagement/EdgeList'),
}

// 根级菜单
const rootRouter = {
  title: 'menu.home',
  path: '/mos',
  component: 'BasicLayout',
  redirect: '/dashboard',
  children: [
    {
      path: '/mos/welcome',
      name: 'welcome',
      component: 'Welcome',
      meta: '{ "hidden": "true" }'
    },
  ]
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表，递归方法
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) =>
  routerMap.map(item => {
    let { meta } = item
    const { title, id, hideChildrenInMenu, redirect } = item
    !meta && (meta = '{}')
    try {
      meta = JSON.parse(meta)
    } catch (error) { }
    const { icon, hidden, permissionId, isSuperAdmin, noMenu, alwaysAccess, back } = meta
    const currentRouter = {
      id,
      title,
      hideChildrenInMenu,
      redirect,
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component: constantRouterComponents[item.component || item.key] || constantRouterComponents[404],

      // meta: 页面标题， 菜单图标， 是否设置对应菜单， 页面权限(供指令权限用，可去掉)
      meta: {
        title,
        icon,
        hidden,
        permissionId,
        isSuperAdmin,
        noMenu,
        alwaysAccess,
        back
      }
    }

    // 如果该路由需要还原查询现场，则需要动态生成对应的store module
    if (storeQueryPages.includes(item.name)) {
      const componentName = item.name.charAt(0).toUpperCase() + item.name.slice(1)
      registerLoadDataModule(componentName)
    }

    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      currentRouter.redirect = item.children[0].path
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = routers => {
  const tempRouter = []
  rootRouter.children = rootRouter.children.concat(routers)
  tempRouter.push(rootRouter)
  console.log(rootRouter, 'fullRouter')
  const fullRouter = generator(tempRouter)
  return fullRouter
}

/**
 * 生成 [路由组名]:[路由数组] 键值对。
 * 路由组：一组路由受到相同权限(permission)控制。
 * 路由组具有以下特点：
 * 1. 每个路由组有一个入口路由和一个或多个附属路由，同组的路由在routerMap里是兄弟节点
 * 2. 如果入口路由有查询数据的功能，那么路由在组内跳转，最后回到入口路由，之前的查询条件需要保留
 * 3. 路由跳出本路由组，再回到本组路由的入口路由，查询条件重置
 *
 * ex: RoleManage和RoleForm属于同一个路由组，其中RoleManage是入口路由
 * @param {*} routerMap
 */
export const generatorRouteGroup = routerMap => {
  const group = {}
  breadFirstTree(
    routerMap,
    jn => {
      const meta = jn.meta || '{}'
      const { permission } = JSON.parse(meta)
      if (!!permission && !Object.hasOwnProperty.call(jn, 'children')) {
        const sortedPerm = permission.sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0))
        for (const item of sortedPerm) {
          if (!Object.hasOwnProperty.call(group, item)) {
            group[item] = [jn]
          } else {
            group[item].push(jn)
          }
        }
      }
      return true
    },
    'children'
  )
  return group
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
// const listToTree = (list, tree, parentId) => {
//   list.forEach((item) => {
//     // 判断是否为父级菜单
//     if (item.parentId === parentId) {
//       const child = {
//         ...item,
//         key: item.key || item.name,
//         children: [],
//       };
//       // 迭代 list， 找到当前菜单相符合的所有子菜单
//       listToTree(list, child.children, item.id);
//       // 删掉不存在 children 值的属性
//       if (child.children.length <= 0) {
//         delete child.children;
//       }
//       // 加入到树中
//       tree.push(child);
//     }
//   });
// };

/**
 * 为需要还原查询条件的page动态创建独立的store module
 * @param {*} name
 */
function registerLoadDataModule(name) {
  window.app.$store.registerModule(name, {
    namespaced: true,
    state: {
      pageParams: {},
      queryParams: {},
      expandedKeys: [],
      selectedKeys: []
    },
    mutations: {
      SET_PAGE_PARAMS: (state, payload) => {
        state.pageParams = payload
      },

      SET_QUERY_PARAMS: (state, payload) => {
        state.queryParams = payload
      },

      SET_EXPANDED_KEYS: (state, payload) => {
        state.expandedKeys = payload
      },

      SET_SELECTED_KEYS: (state, payload) => {
        state.selectedKeys = payload
      }
    },
    actions: {
      StoreInitParams({ commit }, { pageParams, queryParams, expandedKeys, selectedKeys }) {
        commit('SET_PAGE_PARAMS', pageParams)
        commit('SET_QUERY_PARAMS', queryParams)
        commit('SET_EXPANDED_KEYS', expandedKeys)
        commit('SET_SELECTED_KEYS', selectedKeys)
      },

      ResetInitParams({ commit }) {
        commit('SET_PAGE_PARAMS', {})
        commit('SET_QUERY_PARAMS', {})
        commit('SET_EXPANDED_KEYS', [])
        commit('SET_SELECTED_KEYS', [])
      }
    }
  })
}
